package com.restfinder.user.component;

import lombok.Setter;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;
import org.springframework.validation.Errors;
import org.springframework.validation.ValidationUtils;
import org.springframework.validation.Validator;

import com.restfinder.common.component.utils.PropertiesUtils;
import com.restfinder.user.forms.UserForm;
import com.restfinder.user.model.User;
import com.restfinder.user.service.UserService;

@Component
public class UserValidator implements Validator {

	@Autowired
	private UserService userService;
	
	public boolean supports(Class<?> clazz) {
		return UserForm.class.equals(clazz);
	}

	public void validate(Object obj, Errors errors) {
		ValidationUtils.rejectIfEmpty(errors, "user.name", PropertiesUtils.getMessage("user.name.empty"));	
		ValidationUtils.rejectIfEmpty(errors, "user.surname", PropertiesUtils.getMessage("user.surname.empty"));
		ValidationUtils.rejectIfEmpty(errors, "user.username", PropertiesUtils.getMessage("user.username.empty"));
		ValidationUtils.rejectIfEmpty(errors, "user.password", PropertiesUtils.getMessage("user.password.empty"));
		ValidationUtils.rejectIfEmpty(errors, "password2", PropertiesUtils.getMessage("user.password.empty"));
		
		UserForm uf = (UserForm) obj;
		System.out.println(uf.getUser());
		if(!uf.getUser().getPassword().equals(uf.getPassword2())){
			errors.rejectValue("user.password", PropertiesUtils.getMessage("user.password.notmatch"));
		}
		if(!userService.isUsernameUnique(uf.getUser().getUsername(), uf.getUser())){
			errors.rejectValue("user.username", PropertiesUtils.getMessage("user.username.notunique"));
		}
		
		
	}

}
